package com.michaelbulava.TFS.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcsUtil.VcsUtil;
import com.michaelbulava.TFS.vcs.TFSVcs;
import com.michaelbulava.TFS.vcs.exceptions.TFSException;
import com.michaelbulava.TFS.vcs.internal.SharedOperations;
import com.michaelbulava.TFS.vcs.internal.WorkstationHelper;
import com.michaelbulava.TFS.vcs.utils.TFSFileUtil;
import com.michaelbulava.TFS.vcs.utils.TFSUtil;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * Created by MichaelA on 9/29/2015.
 */
public class CheckoutAction extends OnlineRequiredAction{
    /**
     * Implement this method to provide your action handler.
     *
     * @param e Carries information on the invocation place
     */
    @Override
    public void actionPerformed(AnActionEvent e) {
        final Project project = (Project)e.getData(CommonDataKeys.PROJECT);
        final VirtualFile[] files = VcsUtil.getVirtualFiles(e);

        List<FilePath> filePathList = TFSFileUtil.getFilePaths(files);
        final List<VcsException> errors = new ArrayList<>();
        try {
            List<FilePath> orphans = WorkstationHelper.processByWorkspaces(filePathList, false, project,
                    new WorkstationHelper.VoidDelegateProcess() {
                        @Override
                        public void executeRequest(Workspace workspace, List<FilePath> localPaths) throws TFSException {
                            Collection<VcsException> e = SharedOperations.performCheckout(project, workspace, localPaths);
                            errors.addAll(e);
                        }
                    });

            if (!orphans.isEmpty()){
                for(FilePath file : orphans)
                    errors.add(new VcsException(file.getPath() + " does not appear to be mapped."));
            }

            if (!errors.isEmpty())
                AbstractVcsHelper.getInstance(project).showErrors(errors, TFSVcs.VCS_NAME);
        } catch (TFSException e1) {
            AbstractVcsHelper.getInstance(project).showError(new VcsException(e1), TFSVcs.VCS_NAME);
        } finally{

        }
    }
}
